package org.poem.exec.register;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import org.poem.canal.CanalHandleEntry;
import org.poem.exec.annotation.CanalHandle;
import org.reflections.Reflections;

import java.util.Comparator;
import java.util.List;
import java.util.Set;


/**
 * @author poem
 */
public class CanalHandlerRegister {


    /**
     * 获取包扫描类型
     *
     * @param packageName
     * @return
     */
    public static List<CanalHandleEntry> getHandler(TaskRegisterFilter taskRegisterFilter, String packageName) {
        Reflections reflections = new Reflections(packageName);
        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(CanalHandle.class);

        List<CanalHandleEntry> zgTasks = Lists.newArrayList();
        for (Class classes : classesList) {
            CanalHandle task = (CanalHandle) classes.getAnnotation(CanalHandle.class);
            if (task != null) {
                CanalHandleEntry zgTask = new CanalHandleEntry();
                zgTask.setAClass(classes);
                zgTask.setOrder(task.order());
                zgTask.setClassName(classes.getName());
                if (taskRegisterFilter.accept(zgTask)) {
                    zgTasks.add(zgTask);
                }
            }
        }
        CollectionUtil.sort(zgTasks, new Comparator<CanalHandleEntry>() {
            @Override
            public int compare(CanalHandleEntry o1, CanalHandleEntry o2) {
                return o1.getOrder() - o2.getOrder();
            }
        });
        return zgTasks;
    }

}
